package com.zhiqianbao.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.android.moblie.zmxy.antgroup.creditsdk.app.ICreditListener;
import com.google.gson.Gson;
import com.zhiqianbao.credit.sdk.CreditAuthHelper;
import com.zhiqianbao.credit.sdk.DemoPresenter;
import com.zhiqianbao.credit.sdk.DemoView;
import com.zhiqianbao.entity.ZhiMa;
import com.zhiqianbao.utils.Constants;
import com.zhiqianbao.utils.HttpUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import cn.trinea.android.common.util.StringUtils;
import cn.trinea.android.common.util.ToastUtils;
/**
 * Created by befairyliu on 16/1/30.
 */
public class DemoPresenterImpl extends BaseActivity implements DemoPresenter {
    public static final int DATA_FILED=0x123;
    public static final int ZHIMA=0x124;
    public static final int GETSCORE=0x125;
    private Gson gson = new Gson();
    private static final String TAG = "ZHIMA_DemoPresenterImpl";
    private DemoView demoView;
    private Activity activity;
    private String sign;
    private String params;

    public DemoPresenterImpl(Activity activity, DemoView demoView) {
        this.activity = activity;
        this.demoView = demoView;
    }

    @Override
    public void doCreditRequest() {
        String userId = Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "";
        zhiMaData();
    }
    public void zhiMaData(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = new Message();
                Map<String, String> mapParams = new HashMap<>();
                mapParams.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                mapParams.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                String result = HttpUtils.httpPostString(Constants.API_ROOT + "/api/zhima/getZhimaParams",
                        mapParams, DemoPresenterImpl.this);
                if (StringUtils.isBlank(result)) {
                    message.what = DATA_FILED;
                } else {
                    message.what = ZHIMA;
                    ZhiMa data =gson.fromJson(result, ZhiMa.class);
                    message.obj = data;
                }
                postHandler.sendMessage(message);
            }
        }).start();
    }

    public void getScore(final Bundle result){
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = new Message();
                Map<String, String> mapParams = new HashMap<>();
                mapParams.put("params", result.getString("params"));
                mapParams.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                mapParams.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                String result = HttpUtils.httpPostString(Constants.API_ROOT + "/api/zhima/getScore",
                        mapParams, DemoPresenterImpl.this);
                if (StringUtils.isBlank(result)) {
                    message.what = DATA_FILED;
                } else {
                    message.what = GETSCORE;
                    ZhiMa data =gson.fromJson(result, ZhiMa.class);
                    message.obj = data;
                }
                postHandler.sendMessage(message);
            }
        }).start();
    }

    Handler postHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DATA_FILED:
                    showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                    break;
                case ZHIMA:
                    ZhiMa response = (ZhiMa) msg.obj;
                    closeWaitDialog();
                    if (response == null){
                        showShortToast1("网络超时，请再试!");
                    }
                    if (response != null){
                        if (response.getCode().equals("0")) {
                            sign = response.getData().getSign();
                            params = response.getData().getParams();
                            closeWaitDialog();
                            try {
                                final String appId = "1002214";
                                //不过建议auth_code参数组织到biz_params里面进行加密加签。
                                Map<String, String> extParams = new HashMap<>();
                                //请求授权
                                CreditAuthHelper.creditAuth(activity, appId, params, sign, extParams, new ICreditListener() {
                                    @Override
                                    public void onComplete(Bundle result) {
                                        demoView.toastMessage("授权成功");
                                        String params1 = null;
                                        //从result中获取params参数,然后解析params数据,可以获取open_id。
                                        if (result != null) {
                                            Set<String> keys = result.keySet();
                                            String userId = Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "";
                                            getScore(result);
                                        }
                                    }

                                    @Override
                                    public void onError(Bundle result) {
                                        //toast message
                                        demoView.toastMessage("授权错误");
                                        Log.d(TAG, "DemoPresenterImpl.doCreditAuthRequest.onError.");
                                    }

                                    @Override
                                    public void onCancel() {
                                        //toast message
                                        demoView.toastMessage("授权失败");
                                        Log.d(TAG, "DemoPresenterImpl.doCreditAuthRequest.onCancel.");
                                    }
                                });
                            } catch (Exception e) {
                                Log.e(TAG, "DemoPresenterImpl.doCreditAut、、hRequest.exception=" + e.toString());
                            }
                        }
                        else {
                            ToastUtils.show(getApplicationContext(), response.getMsg(), 1);
                        }
            }

                    break;
                case GETSCORE:
                    closeWaitDialog();
                    ZhiMa zhima = (ZhiMa) msg.obj;
                    if (zhima == null) {
                        showShortToast1("网络链接超时，请稍后再试!");
                    }
                    if (activity != null) {
                        startActivity(new Intent(activity, CertificationSdActivity.class));
                        activity.finish();
                    }
                    if (!TextUtils.isEmpty(zhima.toString())) {
                        if (zhima.getCode().equals("0")) {
                            ToastUtils.show(activity, zhima.getMsg(), 1);

                        }
                    }
                    break;
            }
        }
    };
}
